package user

import (
	"common/mildware"
	"common/models"
	"common/validate"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/docModel"
	"strconv"
	"strings"
)

func (h UHandler) UpdateUserInfo(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.UpdateUserInfoReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("User:UpdateUserInfo with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("User:UpdateUserInfo with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//获得ID
	ID, _, _, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("User:UpdateUserInfo mildware.GetCyrrentUserID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	exist, userInfo, err := h.M.UserCheckId(ID)
	if !exist {
		resp.SendCode(c, models.CodeUserNotExist)
		return
	}
	userInfo.Name = req.Name
	userInfo.NickName = req.NickName
	userInfo.Sex = req.Sex
	userInfo.Phone = req.Phone
	userInfo.Text = req.Text
	//更新
	if err := h.M.UserUpdateById(userInfo); err != nil {
		zap.L().Error("User:UpdateUserInfo  h.M.UserUpdateById", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
func (h UHandler) ExitGroup(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.ExitGroupReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("User:ExitGroup with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("User:ExitGroup with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//用户信息
	exist, info, err := h.M.UserCheckId(req.UserID)
	if err != nil {
		zap.L().Error("User:ExitGroup  h.M.UserCheckId", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		//更新用户群聊
		groups := strings.Split(info.Groups, "|")
		info.Groups = models.RemoveList(req.GroupID, groups)
		fmt.Printf("%+v.---%v", groups, info.Groups)
		//更新用户
		err := h.M.UserSaveById(info)
		if err != nil {
			zap.L().Error("User:ExitGroup  h.M.UserUpdateById", zap.Error(err))
			resp.SendServerBusy(c)
			return
		}
	}
	//获得群聊信息
	gInfo, err := h.M.GroupSelectByID(req.GroupID)
	if err != nil {
		zap.L().Error("User:ExitGroup  h.M.GroupSelectByID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	peoplesList := strings.Split(gInfo.Peoples, "|")
	gInfo.Peoples = models.RemoveList(strconv.Itoa(int(info.ID)), peoplesList)
	//更新群聊
	err = h.M.GroupSaveByID(gInfo)
	if err != nil {
		zap.L().Error("User:ExitGroup  h.M.GroupSaveByID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
